package ru.acme.lab13;

import ru.acme.lab13.domain.account.CheckingAccount;
import ru.acme.lab13.domain.account.SavingAccount;
import ru.acme.lab13.domain.bank.Bank;
import ru.acme.lab13.domain.client.Client;
import ru.acme.lab13.domain.client.Gender;
import ru.acme.lab13.service.bank.BankService;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;

public class BankApplication {
	
	private static final String BANK_SERIALIZATION_FILE_NAME = "C:\\bank.ser";

    // TODO [MY]  Arg '–loadbank path_to_feed_file' should be supported (see p.2).
	public static void main(String[] args) {

		String feedFileName = null;
		String serializedBankFileName = null;
		for (int i = 0; i < args.length; ++i) {
			if ((args[i].equals("-loadfeed")) && (i < args.length - 1)) {
				feedFileName = args[i + 1];
			}
			if ((args[i].equals("-loadbank")) && (i < args.length - 1)) {
				serializedBankFileName = args[i + 1];
			}
		}
		Bank bank = null;
		if (serializedBankFileName != null) {
			try {
				bank = BankService.readBank(serializedBankFileName);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		if (bank == null) {
			bank = new Bank();
		}
		if (feedFileName != null) {
			try {
				BankService.loadClientsFromFile(bank, feedFileName);
			} catch (FileNotFoundException e) {
				System.out.println("File " + feedFileName + " not found");
			} catch (ParseException e) {
				System.out.println("File " + feedFileName + " contains incorrect string: " + e.getMessage());
			}
		}
		
		try {
			BankService.writeBank(bank, BANK_SERIALIZATION_FILE_NAME);
			Bank bank1 = BankService.readBank(BANK_SERIALIZATION_FILE_NAME);
			assert(bank.getClients().equals(bank1.getClients()));

			BankService.addClient(bank, new Client("Mary", Gender.FEMALE, new CheckingAccount(30, 20)));			
			bank.getClients().get(0).getAccounts().get(0).deposit(10);
			BankService.writeBank(bank, BANK_SERIALIZATION_FILE_NAME);
			bank1 = BankService.readBank(BANK_SERIALIZATION_FILE_NAME);
			assert(bank.getClients().equals(bank1.getClients()));
			
			BankService.addClient(bank, new Client("Bill", Gender.MALE, new SavingAccount(30)));
			BankService.addClient(bank1, Client.parseClient("accounttype=s;balance=30.0;-;name=Bill;gender=m"));
			assert(bank.getClients().equals(bank1.getClients()));
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		System.out.println("OK!");
	}

}
